package com.lams.jdbc;

import java.sql.PreparedStatement;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.sql.ResultSet;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.access.ContextBeanFactoryReference;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.support.JdbcUtils;
import org.springframework.util.Assert;
import org.xml.sax.InputSource;

public class BaseDAO extends JdbcDaoSupport implements IBaseDAO {
	private static Logger logger =Logger.getLogger(BaseDAO.class);
	
	@Override
	public void freeConnection() throws SQLException{
		JdbcUtils.closeConnection(super.getConnection());
	}
	
	@Override
	public int executeUpdate(String sql) throws SQLException{
		Assert.hasText(sql);
		if(logger.isDebugEnabled()){
			logger.debug("执行语句：["+sql+"]");
		}
		return super.getJdbcTemplate().update(sql);
	}
//	public void setMaxRows(int count){
//		int rows = super.getJdbcTemplate().getMaxRows();
//		if(rows<count){
//			super.getJdbcTemplate().setMaxRows(count);
//		}
//	}
	@Override
	public int[] batchUpdate(final String sql,final List source) throws SQLException{
		return super.getJdbcTemplate().batchUpdate(sql,new BatchPreparedStatementSetter() {
			@Override
			public void setValues(PreparedStatement ps, int i)
					throws SQLException {
				Map item = (Map)source.get(i);
				String s = sql;
				
				for(Iterator<String> iterator = item.keySet().iterator();iterator.hasNext();){
					String key = iterator.next();
					String value = String.valueOf(item.get(key));
					s = s.replaceAll("@@"+key+",", value);
				}
				if(logger.isDebugEnabled()){
					logger.debug("执行语句：["+sql+"]");
				}
				ps.addBatch(s);
			}
			@Override
			public int getBatchSize() {
				return source.size();
			}
		});
	}

	@Override
	public List executeQuery(String sql) throws SQLException{
		Assert.hasText(sql);
		if(logger.isDebugEnabled()){
			logger.debug("执行语句：["+sql+"]");
		}
		return super.getJdbcTemplate().query(sql, new RowMapMapper());
	}
	
	private static final class RowMapMapper implements ParameterizedRowMapper{

		@Override
		public Object mapRow(ResultSet rs, int index) throws SQLException {
			Map item = new HashMap();
			ResultSetMetaData metaData = rs.getMetaData();
			String key = "",value = "";
			for (int i = 0; i < metaData.getColumnCount(); i++) {
				key = metaData.getColumnName(i+1).toUpperCase();
				//metaData.getColumnName(i+1)
				value = rs.getString(key);
				item.put(key, value);
			}
			return item;
		}
		
	}

	@Override
	public int[] batchUpdate(String[] sqls) {
		// TODO Auto-generated method stub
		return super.getJdbcTemplate().batchUpdate(sqls);
	}
//	public static void main(String[] args) {
//		Resource resource = new FileSystemResource("lams/WEB-INF/config/applicationContext.xml");
//		BeanFactory factory = new XmlBeanFactory(resource);
//		IBaseDAO dao = (BaseDAO) factory.getBean("baseDao");
//		try {
//			dao.executeQuery("SELECT ROWNUM NUM FROM DUAL WHERE ROWNUM BETWEEN 1 AND 5001");
//		} catch (SQLException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		
//	}

	@Override
	public Map executeQueryRecode(String sql) throws SQLException {
		return super.getJdbcTemplate().queryForMap(sql);
	}
}
